import * as services from 'services/relation';
import { Toast } from 'antd-mobile';

export default {

  namespace: 'relation',

  state: {
    Requests: [],
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

  effects: {

    *request({ payload }, { call, put }) {
      let hospitalId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).hospitalId;
      let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
      let data = yield call(services.requestRelation, hospitalId, patientId);
      if (!data) {
        data = [];
      }
      yield put({
        type: 'save',
        payload: {
          Requests: data.data,
        },
      });
    },

    *accept({ payload:{ id} }, { call, put }) {
      const data = yield call(services.acceptRelation, id);
    },

    *send({ payload: { doctorId, patientId } }, { call, put }) {
      patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
      const data = yield call(services.sendRelation, doctorId, patientId);
      if(data.code == 200){
          Toast.success('申请发送成功');
      }else{
          Toast.fail(data.message);
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query, ...rest }) => {
        if (/newdoctor$/.test(pathname)) {
          dispatch({ type: 'relation/request' });
        }
      });
    },
  },
}
